import json
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
from requests import cookies
import openpyxl
import requests
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
class score():
    def __init__(self):
        self.cookie_path='.\data\cookies.txt'
    def openWEB(self):
        desired_capabilities = DesiredCapabilities.CHROME
        desired_capabilities["pageLoadStrategy"] = "none"
        option=webdriver.ChromeOptions()
        # option.add_argument('--headless')
        option.add_argument("–incognito")
        option.add_argument('--user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"')
        diver=webdriver.Chrome(options=option,executable_path='./data/chromedriver.exe')
        return diver
    def save_cookie(self,user):
        self.USERID=user[0]
        self.PASSWORD=user[1]
        diver=self.openWEB()
        diver.get('http://authserver.xju.edu.cn/authserver/login')
        WebDriverWait(diver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="casLoginForm"]/p[5]/button')))
        WebDriverWait(diver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="casLoginForm"]/p[6]/div/ins')))
        WebDriverWait(diver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="password"]')))
        WebDriverWait(diver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="username"]')))
        diver.find_element_by_xpath('//*[@id="username"]').send_keys(self.USERID)
        diver.find_element_by_xpath('//*[@id="password"]').send_keys(self.PASSWORD)
        diver.find_element_by_xpath('//*[@id="casLoginForm"]/p[6]/div/ins').click()
        diver.find_element_by_xpath('//*[@id="casLoginForm"]/p[5]/button').click()
        time.sleep(2)
        if diver.current_url=='http://authserver.xju.edu.cn/authserver/index.do':
            diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/*default/index.do?')
            try:
                WebDriverWait(diver, 30).until(EC.element_to_be_clickable((By.XPATH, '/html/body/main/article/section/div/div[2]/div[3]/button')))
            except:
                diver.quit()
                return 2
            cookie=diver.get_cookies()
            cookies=json.dumps(cookie)
            with open(self.cookie_path, 'w') as f:
                f.write(cookies)
            print('cookie获取完成')
            diver.quit()
            return 1
        else:
            diver.quit()
            return 0
    def calculation(self,str,p):
        if p==0:
            try:
                num=float(str)
            except:
                return 1
            if num>60:
                a=num//10-5
                b=num%10/10
                return a+b
            else:
                return 0
        elif p==1:
            try:
                num=float(str)
            except:
                num=0
            return num
    def page_handle(self,page):
        datalist=[]
        total_XF=0
        total_ZCJ=0
        js_data=page
        dict_data=json.loads(js_data)
        N_data=dict_data['datas']['cxxscj']['rows']
        for i in N_data:
            if i not in datalist:
                datalist.append(i)
        for i in datalist:
            total_XF+=self.calculation(i['XF'],1)
        for i in datalist:
            total_ZCJ+=self.calculation(i['ZCJ'],0)*self.calculation(i['XF'],1)/total_XF
        return (total_XF,round(total_ZCJ,2))
    def find(self,XH,XN,XQ):
        self.all_class=[]
            # ---------登录查询页面首----------#
        post_data={
            'XSBH':XH,
            'XQ':XQ,
            'XN':XN,
            'pageSize':'150',
            'pageNumber':'1'
        }
        url='http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do'
        header = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"
}
        s = requests.Session()
        # r = s.post(url,headers=header,timeout=8)
        c = requests.cookies.RequestsCookieJar()
        with open(self.cookie_path, 'r') as f:
            cookielist=json.loads(f.read())
            for cookies in cookielist:
                c.set(cookies['name'], cookies['value'], path=cookies['path'], domain=cookies['domain'])
                s.cookies.update(c)
        r = s.post(url,data=post_data,headers=header,timeout=8)
        print('r:',r.text)
            # ---------登录查询页面尾----------#
        # if (diver.current_url!='http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH+'&XN='+XN+'&XQ='+XQ+'&pageSize=150&pageNumber=1'):
        #     print('已有的cookie已失效，正在获取最新cookie，请稍等片刻···')
        #     self.save_cookie(())
        #     # ---------登录查询页面首----------#
        #     with open(r'C:\Users\HUAWEI\Desktop\text\cookies.txt','r') as f:
        #         cookielist=json.loads(f.read())
        #         for cookies in cookielist:
        #             diver.add_cookie(cookies)
        #     diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH+'&XN='+XN+'&XQ='+XQ+'&pageSize=150&pageNumber=1')
            # ---------登录查询页面尾----------#
        js_data=r.text
        dict_data=json.loads(js_data)
        N_data=dict_data['datas']['cxxscj']['rows']
        for i in N_data:
            if i not in self.all_class:
                self.all_class.append(i)
        return self.all_class
        # diver.get('http://authserver.xju.edu.cn/authserver/login?service=http%3A%2F%2Fehall.xju.edu.cn%2Flogin%3Fservice%3Dhttp%3A%2F%2Fehall.xju.edu.cn%2Fnew%2Findex.html')
        # time.sleep(8)
        # diver.find_element_by_xpath('//*[@id="username"]').send_keys(self.USERID)
        # diver.find_element_by_xpath('//*[@id="password"]').send_keys(self.PASSWORD)
        # time.sleep(3)
        # diver.find_element_by_xpath('//*[@id="casLoginForm"]/p[5]/button').click()
        # time.sleep(8)
        # diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/*default/index.do?')
        # time.sleep(8)
        # diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+self.XH+'&XN='+self.XN+'&XQ='+self.XQ+'&pageSize=150&pageNumber=1')
        # time.sleep(5)
        # data=diver.page_source
        # diver.quit()
    def find_all(self,XH_list,XN,XQ):
        post_data={
            'XSBH':XH_list[0],
            'XQ':'1',
            'XN':'2019',
            'pageSize':'150',
            'pageNumber':'1'
        }
        data_list={}
        url='http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do'
        header = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"
        }
        s = requests.Session()
        # r = s.post(url,headers=header,timeout=8)
        c = requests.cookies.RequestsCookieJar()
        with open(self.cookie_path, 'r') as f:
            cookielist=json.loads(f.read())
            for cookies in cookielist:
                c.set(cookies['name'], cookies['value'], path='/', domain='ehall.xju.edu.cn')
                s.cookies.update(c)
        r = s.post(url,data=post_data,headers=header,timeout=8)
        if XQ=='0' and str(r)=='<Response [200]>':
            for XH in XH_list:
                post_data={
            'XSBH':XH,
            'XQ':XQ,
            'XN':XN,
            'pageSize':'150',
            'pageNumber':'1'
        }
                # 查询第一学期信息
                url1='http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do'
                data1=s.post(url1,data=post_data,headers=header,timeout=8).text
                # 查找第二学期信息
                url2='http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do'
                data2=s.post(url2,data=post_data,headers=header,timeout=8).text
                # 成绩转化统计
                XQ1_data=self.page_handle(data1)
                XQ2_data=self.page_handle(data2)
                total_XF=XQ1_data[0]+XQ2_data[0]
                total_ZCJ=(XQ1_data[1]*XQ1_data[0]/total_XF)+(XQ2_data[1]*XQ2_data[0]/total_XF)
                data_list[XH]=(total_XF,round(total_ZCJ,2))
        elif XQ=='1' and str(r)=='<Response [200]>':
            for XH in XH_list:
                post_data={
            'XSBH':XH,
            'XQ':XQ,
            'XN':XN,
            'pageSize':'150',
            'pageNumber':'1'
        }
                url1='http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do'
                data1=s.post(url1,data=post_data,headers=header,timeout=8).text
                XQ1_data=self.page_handle(data1)
                print(XQ1_data)
                data_list[XH]=XQ1_data
        elif XQ=='2' and str(r)=='<Response [200]>':
            for XH in XH_list:
                url2='http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do'
                post_data={
            'XSBH':XH,
            'XQ':XQ,
            'XN':XN,
            'pageSize':'150',
            'pageNumber':'1'
        }
                data2=s.post(url2,data=post_data,headers=header,timeout=8).text
                XQ2_data=self.page_handle(data2)
                print(XQ2_data)
                data_list[XH]=XQ2_data
        print(data_list)
        return data_list
    def XQ_point(self,XH,XN,XQ):
        data=self.find(XH,XN,XQ)
        print(data)
        total_XF=0
        total_ZCJ=0
        for i in data:
            total_XF+=self.calculation(i['XF'],1)
        for i in data:
            total_ZCJ+=self.calculation(i['ZCJ'],0)*self.calculation(i['XF'],1)/total_XF
        return ((total_XF,round(total_ZCJ,2)),data)
    def XN_point(self,XH,XN):
        XQ1_data=self.XQ_point(XH,XN,'1')[0]
        XQ2_data=self.XQ_point(XH,XN,'2')[0]
        total_XF=XQ1_data[0]+XQ2_data[0]
        total_ZCJ=(XQ1_data[1]*XQ1_data[0]/total_XF)+(XQ2_data[1]*XQ2_data[0]/total_XF)
        print('第一学期：{0} , 第二学期：{1}'.format(XQ1_data,XQ2_data))
        return (total_XF,round(total_ZCJ,2))
    def text_cookie(self):
        post_data={
            'XSBH':'0',
            'XQ':'1',
            'XN':'2019',
            'pageSize':'150',
            'pageNumber':'1'
        }
        url='http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do'
        header = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"
}
        s = requests.Session()
        # r = s.post(url,headers=header,timeout=8)
        c = requests.cookies.RequestsCookieJar()
        with open(self.cookie_path, 'r') as f:
            cookielist=json.loads(f.read())
            for cookies in cookielist:
                c.set(cookies['name'], cookies['value'], path='/', domain='ehall.xju.edu.cn')
                s.cookies.update(c)
        r = s.post(url,data=post_data,headers=header,timeout=8)
        if r.url==url:
            return 1
        else:
            return 0
    def sort_data(self,XH_list,XN,XQ):
        new_data={}
        list=[]
        dict=self.find_all(XH_list,XN,XQ)
        for i in dict:
            new_data[i]=dict[i][1]
        tuple = zip(new_data.values(),new_data.keys())
        rank=sorted(tuple,reverse=True)
        for i in rank:
            list.append('学号：{0} 绩点：{1}'.format(i[1],i[0]))
        return list
    def import_data(self,route):
        XH_list=[]
        if '.xlsx' in route:
            original_data=openpyxl.load_workbook(route)['Sheet1']
            maxrow=original_data.max_row
            for i in range(2,maxrow+1):
                if str(original_data['A'+str(i)].value) not in XH_list:
                    XH_list.append(str(original_data['A'+str(i)].value))
            return XH_list
        else:
            pass
    def text_web(self):
        try:
            self.XQ_point('0','0','1')
            return True
        except BaseException as e:
            print(e)
            return False



